<template>
  <mu-container class="button-wrapper">
    <div class="index-img-box">
      <img :src="indeximg" alt/>
    </div>
    <equipmentcode ref="equipmentcode" @equiperror="handleEquipError"></equipmentcode>
    <baidu-map
      class="map"
      :center="center"
      :zoom="13"
      :scroll-wheel-zoom="true"
      @ready="getUserLocation"
    >
      <bm-scale anchor="BMAP_ANCHOR_BOTTOM_LEFT"></bm-scale>
      <bm-marker :position="center"></bm-marker>
    </baidu-map>

    <mu-flex justify-content="center" align-items="center" class="btn-box">
      <mu-button fab color="white" class="no-show c-btn" @click="showsm()">
        <svg class="icongeneral" aria-hidden="true">
          <use xlink:href="#icon-scan"></use>
        </svg>
      </mu-button>
      <mu-button class="scan-btn btn" @click="OpenScan(callback)" v-show="smshow">扫码充电</mu-button>
      <mu-button class="scan-btn btn" @click="showcodediv" v-show="srshow">输入充电桩编号</mu-button>
      <mu-button fab color="white" class="no-show c-btn" @click="showsr()">
        <span class="iconfont icon-dianji"></span>
      </mu-button>
    </mu-flex>
    <div class="bottom">
      <mu-bottom-nav>
        <mu-bottom-nav-item title="首页" icon=" " to="/sweep" id="home"></mu-bottom-nav-item>
        <mu-bottom-nav-item title="充值" icon=" " to="/vainvest" id="chongz"></mu-bottom-nav-item>
        <mu-bottom-nav-item title="我的" icon=" " to="/mine" id="wode"></mu-bottom-nav-item>
      </mu-bottom-nav>
    </div>
  </mu-container>
</template>

<script>
    import Vue from "vue";
    import BaiduMap from "vue-baidu-map";
    import indeximg from "@/assets/image/Booking.png";
    import equipmentcode from "@/components/global/equipmentcode";
    import store from "store";
    import {Toast, Dialog} from "vant";
    import "vant/lib/toast/style/index";
    import "vant/lib/dialog/style/index";

    Vue.use(BaiduMap, {
        ak: "kHuT1n634XyhUTcOU3oPa2ovhKbOK5NN"
    });
    export default {
        data() {
            return {
                indeximg: indeximg,
                smshow: true,
                srshow: false,
                cardid: "",
                pageUrl: "",
                center: {lng: 121.6292529148, lat: 31.2035397816}
            };
        },
        components: {
            equipmentcode: equipmentcode
        },
        methods: {
            handleEquipError() {
                Dialog.alert({
                    title: '提示',
                    message: '设备网络差'
                }).then(() => {
                    // on close
                });
            },
            showcodediv() {
                this.$refs.equipmentcode.showPanel();
            },
            showsm() {
                this.smshow = true;
                this.srshow = false;
            },
            showsr() {
                this.srshow = true;
                this.smshow = false;
            },
            getvar(url, par) {
                var urlsearch = url.split('?');
                if (!urlsearch[1]) {
                    return false
                }
                var pstr = urlsearch[1].split('&');
                for (var i = pstr.length - 1; i >= 0; i--) {
                    var tep = pstr[i].split("=");
                    if (tep[0] === par) {
                        return tep[1];
                    }
                }
                return false;
            },
            callback(res) {
                var scanid = this.getvar(res, 'scanid')
                if (!scanid) {
                    return false
                }
                this.$api.getChargingPileData(scanid).then(res => {

                    if (res.data.code == 2004) {
                        Dialog.alert({
                            title: '提示',
                            message: '设备网络差'
                        }).then(() => {
                            // on close
                        });
                        return;
                    }
                    if (res.data.code == 6005) {
                        Toast({
                            message: res.data.msg,
                            duration: 2000
                        })
                        this.$router.push("/bindphone")
                    }
                    if (res.data.code != 0) {
                        Toast(res.data.msg);
                        return;
                    }
                    this.$store.dispatch("setChargingID", scanid);
                    //Toast("充电桩编号无误,请选择充电端口");
                    this.$router.push("/success");
                });
            },
            OpenScan(fn) {

                wx.scanQRCode({
                    // 微信扫一扫接口
                    needResult: 1, //返回扫描结果，
                    scanType: ["qrCode", "barCode"],
                    success: function (res) {

                        fn(res.resultStr);

                    },
                    fail: function (res) {
                        alter(res)
                    }
                });
            },
            getUserLocation({BMap, map}) {
                var that = this
                setTimeout(function () {
                    wx.getLocation({
                        type: 'wgs84',
                        success: function (res) {
                            that.center.lng = res.longitude
                            that.center.lat = res.latitude
                        },
                        fail: function (res) {

                        }
                    });
                }, 1000)
            }


        },
        created() {
            if (typeof window.entryUrl === 'undefined' || window.entryUrl === '') {
                window.entryUrl = location.href.split('#')[0]
            }
            // 进行签名的时候  Android 不用使用之前的链接， ios 需要
            let signUrl = /(Android)/i.test(navigator.userAgent) ? location.href.split('#')[0] : window.entryUrl;
            this.pageUrl = signUrl
            this.$api.wxOpenWxJsApi(signUrl).then(res => {
                let data = res.data.result;

                // alert( location.href.split('#')[0] )
                // if (data.statusCode == 1) {
                this.$wx.config({
                    debug: false,
                    appId: data.appId, // 公众号的唯一标识
                    timestamp: data.timestamp, // 生成签名的时间戳
                    nonceStr: data.noncestr, // 生成签名的随机串
                    signature: data.signature, // 签名
                    jsApiList: ["scanQRCode", "chooseWXPay"] // 需要使用的JS接口列表
                });
                // }
            });

            wx.ready(function () {
                wx.checkJsApi({
                    //是否支持指定JS接口
                    jsApiList: ["scanQRCode"],
                    success: function (res) {
                        if (res.checkResult.scanQRCode == true) {
                        } else {
                            alter("抱歉，当前客户端版本不支持扫一扫");
                        }
                    },
                    fail: function (res) {
                        // 失败时处理

                        alter("fail" + res);
                    }
                });
            });
            /* 处理失败验证 */
            wx.error(function (res) {
                console.log("配置验证失败: " + res.errMsg);
            });
            if (!this.$store.state.ChargingID) {
                var that = this
                setTimeout(function () {
                    that.callback(that.pageUrl)
                }, 1000)
            }
        },
        watch: {
            cardid: function (v) {
                Toast(v);

                this.$api.getChargingPileData(res.resultStr).then(res => {
                    if (res.data.code == 2000) {
                        Toast("无此充电桩");
                        this.value = "";
                        return;
                    } else if (res.data.code == 2004) {
                        Dialog.alert({
                            title: '提示',
                            message: '设备网络差'
                        }).then(() => {
                            // on close
                        });
                    } else {
                        this.$store.dispatch("setChargingID", this.value);
                        // this.$alert.alert('充电桩编号无误', 'Alert');
                        Toast("充电桩编号无误,请选择充电端口");
                        this.$router.push("/success");
                    }
                });
            }
        }
    };
</script>

<style>
  .bottom {
    display: block;
  }
</style>
